<?php defined( 'BASEPATH' ) or die( 'Restricted' );

/*
This code is copyright 2009-2010 by TMLA INC.  ALL RIGHTS RESERVED.
Please view license.txt in /tgsf_core/legal/license.txt or
http://tgWebSolutions.com/opensource/tgsf/license.txt
for complete licensing information.
*/


function getHtmlTitle( $htmlPage, $default = 'No Title' )
{
    $match = array();
    return preg_match( '/<title>(.+?)<\/title>/is', $htmlPage, $match) ? $match[1] : $default;
}

function dereferenceUrl( $_url, $depth = 0, $retries = 0 )
{
	if ( $_url == '404' )
	{
		return $_url;
	}

	if ( $depth > config( 'max_redirects' ) )
	{
		return false;
	}
	
	if ( $retries > config( 'max_tries') )
	{
		return 'too-many-retries';
	}
	if ( $_url instanceof tgsfDataSource )
	{
		$url = (string)$url->url;
	}
	else
	{
		$url = (string)$_url;
	}

	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6' );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_HEADER, true );
	curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, false );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
	curl_setopt($ch, CURLOPT_COOKIEFILE, config( 'cookie_file' ) );
	curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0); // we don't care about verifying the cert

	$response = curl_exec($ch);

	if ( curl_getinfo( $ch, CURLINFO_HTTP_CODE ) == 404 )
	{
		return '404';
	}
	
	if ( $response == false )
	{
		echo curl_error( $ch );
		var_dump( $retries );
		exit();
	}

	list( $headers,$response ) = explode( "\r\n\r\n", $response );
	if( preg_match( '#Location: (.*)#', $headers, $r ) )
	{
		if ( starts_with( $r[1], 'http' ) == false )
		{
			$r[1] = rtrim( $url, '/' ) . '/' . $r[1];
		}

		return dereferenceUrl( trim( $r[1] ), $depth+1, $retries );
	}

	$ds = dsFactory::ds();
	$ds->setVar( 'url', $url );
	$ds->setVar( 'title', getHtmlTitle( $response, $url ) );
	return $ds;
}
